package com.example.boardroom.demo;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.ArrayMap;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ServiceUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.example.boardroom.R;
import com.example.boardroom.serial.table.DAM3200Table;
import com.example.boardroom.serial.table.ModbusRtu.ModBusBean;
import com.example.boardroom.serial.table.ModbusRtu.ParseSystemUtil;
import com.example.boardroom.serial.table.adapter.DAM3200Adapter;
import com.example.boardroom.serial.table.adapter.DAM3200NodeBean;
import com.example.boardroom.serial.table.manager.DAM3200Manager;
import com.example.boardroom.serial.table.other.SimpleService;
import com.example.boardroom.serial.table.other.UpDataEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.utils.ByteUtil;

public class MainActivity2 extends AppCompatActivity {


    private DAM3200Adapter adapter;
    private RecyclerView recyclerview;
    private TextView tv_refreshTime;
    private Button btn_test, btn_open, btn_close, btn_send;
    private SerialHelper serialHelper;//串口通信辅助类
    EditText edit_sport;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        tv_refreshTime = findViewById(R.id.tv_refreshTime);
        btn_test = findViewById(R.id.btn_test);
        edit_sport=findViewById(R.id.edit_sport);
        EventBus.getDefault().register(this);
        btn_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(new UpDataEvent("01", "0101040E000818FEF3"));
            }
        });


        btn_open = findViewById(R.id.btn_open);
        btn_close = findViewById(R.id.btn_close);
        btn_send = findViewById(R.id.btn_send);
        btn_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                init(edit_sport.getText().toString().trim());
                try {
                    serialHelper.open();
                    ToastUtils.showShort("串口打开成功");
                } catch (Exception e) {
                    ToastUtils.showShort("串口打开失败"+e);
                    e.printStackTrace();
                    serialHelper=null;
                }
            }
        });

        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (serialHelper.isOpen()) {
                    serialHelper.close();
                    ToastUtils.showShort("关闭串口");
                }
            }
        });

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                serialHelper.sendHex("0105000CFF004C39");
            startActivity(new Intent(MainActivity2.this,MainActivity3.class));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initAdapter();
//        if (!ServiceUtils.isServiceRunning(SimpleService.class)) {
//            ServiceUtils.startService(SimpleService.class);
//        }
    }

    private void initAdapter() {
        recyclerview = findViewById(R.id.recyclerview);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        recyclerview.setLayoutManager(gridLayoutManager);
        adapter = new DAM3200Adapter(getEntity());
        recyclerview.setAdapter(adapter);
    }

    private List<BaseNode> getEntity() {
        //总的 list，里面放的是 FirstNode
        List<BaseNode> list = new ArrayList<>();
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));

        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));

        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));

        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));

        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));

        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));
        list.add(new DAM3200NodeBean("名字", "电气:1", "程序:0", "断电", "0"));


        return list;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null!=serialHelper){
            if (serialHelper.isOpen()){
                serialHelper.close();
            }

        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void UpDataEvent(UpDataEvent event) {
        LogUtils.dTag("lufeiupevent", event.frame);
        String toHex = event.frame;
        if (event.port.equalsIgnoreCase("01")) {
            tv_refreshTime.setText(String.format("刷新时间: %s", TimeUtils.getNowString()));
//            long timeSpanByNow = TimeUtils.getTimeSpan(ConfigureTable.MonitoringTime, TimeUtils.getNowString(), TimeConstants.MSEC);
//            tv_cumulativeTime.setText(String.format("当次累计监测时间: %s", ParseSystemUtil.millisecondsConvertToDHMS(Math.abs(timeSpanByNow))));

            String substring = toHex.substring(0, 4);
            if (!substring.equals("0101")) {
                return;
            }
            DAM3200Table dam3200Table = new DAM3200Table("", toHex);
            adapter.setNewInstance(upData(dam3200Table));
        }
    }

    private List<BaseNode> upData(DAM3200Table table) {
        HashMap<String, String> hashMap = table.getHashMap();

        Iterator<Map.Entry<String, String>> entries = hashMap.entrySet().iterator();

        List<BaseNode> list = new ArrayList<>();
        int pos = 0;
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            list.add(new DAM3200NodeBean("名字", "电气:" + (pos + 1), "程序:" + pos, entry.getValue(), "0"));
            ++pos;
        }
        return list;
    }


    private void init(String xxx) {
        serialHelper = new SerialHelper("/dev/bus/usb/001/0012", 9600) {
            @Override
            protected void onDataReceived(ComBean paramComBean) {
                String toHex = ByteUtil.ByteArrToHex(paramComBean.bRec);
                ToastUtils.showShort("收到:"+toHex);
                try {
                    String port = toHex.substring(0, 2);
                    switch (port) {
                        case "01":
                            //全组状态查询发送给逻辑,但是单条命令反馈信息不需要发送给逻辑
                            if ((toHex.length() == 18) || (toHex.startsWith("010104"))) {
                                EventBus.getDefault().postSticky(new UpDataEvent(port, toHex));
//                                DAM3200Table dam3200Table = new DAM3200Table("", toHex);

                            }
                            LogUtils.dTag("lufeimmmx DAM3200:\n", toHex);
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        serialHelper.setStickPackageHelper(is -> {
            try {
                int available = is.available();
                if (available > 0) {
                    byte[] buffer = new byte[available];
                    int size = is.read(buffer);
                    if (size > 0) {
                        return buffer;
                    }
                } else {
                    SystemClock.sleep(400);//等待1.5秒
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        });
    }

}
